package com.boc.ewr.business.service.impl;

import com.aliyuncs.endpoint.location.transform.v20150612.DescribeEndpointsResponseUnmarshaller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.boc.ewr.bcimp.entity.*;
import com.boc.ewr.bcimp.service.*;
import com.boc.ewr.business.entity.CusmTagRelation;
import com.boc.ewr.business.mapper.CusmTagRelationMapper;
import com.boc.ewr.business.service.ICusmTagRelationService;
import com.boc.ewr.uniapp.api.service.IBusCusmInfoApiService;
import com.boc.ewr.util.file.enumeration.CompanyStatusEnum;
import io.swagger.models.auth.In;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @Description: 对公账户标签关系表
 * @Author: jeecg-boot
 * @Date: 2023-05-31
 * @Version: V1.0
 */
@Service
public class CusmTagRelationServiceImpl extends ServiceImpl<CusmTagRelationMapper, CusmTagRelation> implements ICusmTagRelationService {

    private final static long newCusmDaysMark = 143L;

    @Autowired
    private CusmTagRelationMapper cusmTagRelationMapper;

    @Autowired
    private IBusAcctInfoService busAcctInfoService;

    @Autowired
    private ICusmTagListService cusmTagListService;

    @Autowired
    private IQccQryAllService qccQryAllService;

    @Autowired
    private ICacService cacService;

    @Autowired
    private ICaRtnListService caRtnListService;

    @Override
    public void updateTagCusmNm(String cusmNm) {
        List<BusAcctInfo> busAcctInfoList = busAcctInfoService.list(
                new LambdaQueryWrapper<BusAcctInfo>()
                        .eq(BusAcctInfo::getCusmNm, cusmNm)
                        // 根据开户日期排序
                        .orderByAsc(BusAcctInfo::getOacctDate)
        );

        if (busAcctInfoList.size() > 0) {
            BusAcctInfo busAcctInfo = busAcctInfoList.get(0);
            this.removeOldTag(busAcctInfo);
            this.genAcctTag(busAcctInfo);
            this.genriskTag(busAcctInfo);
        }
    }

    @Override
    public Map<String, List<CusmTagList>> queryTageByCusmNm(String cusmNm) {
        List<BusAcctInfo> busAcctInfoList = busAcctInfoService.list(
                new LambdaQueryWrapper<BusAcctInfo>()
                        .eq(BusAcctInfo::getCusmNm, cusmNm)
                        // 根据开户日期排序
                        .orderByAsc(BusAcctInfo::getOacctDate)
        );
        Map<String, List<CusmTagList>> map = new HashMap();
        if (busAcctInfoList.size() > 0) {
            List<String> tagIdList = this.list(
                            new LambdaQueryWrapper<CusmTagRelation>()
                                    .eq(CusmTagRelation::getBusCusmInfoId, busAcctInfoList.get(0).getId())
                    ).stream()
                    .map(CusmTagRelation::getCusmTagId)
                    .collect(Collectors.toList());
            List<CusmTagList> acctTagList = new ArrayList<>();
            List<CusmTagList> riskTagList = new ArrayList<>();
            if (tagIdList.size() > 0) {
                List<CusmTagList> tagLists = cusmTagListService.listByIds(tagIdList);
                for (CusmTagList tagList : tagLists) {
                    if ("账户特征".equals(tagList.getTagType())) {
                        acctTagList.add(tagList);
                    } else if ("风险特征".equals(tagList.getTagType())) {
                        riskTagList.add(tagList);
                    }
                }
            }

            map.put("账户特征", acctTagList);
            map.put("风险特征", riskTagList);
        }
        return map;
    }


    // 以下为更新省行标签的方法
    // 删除之前的数据
    private void removeOldTag(BusAcctInfo busAcctInfo) {
        // 删除之前的省行标签
        cusmTagRelationMapper.deleteCusmTagRelationByBusId(busAcctInfo.getId());
    }

    // 账户特征
    private void genAcctTag(BusAcctInfo busAcctInfo) {
        this.getBusStatusTag(busAcctInfo);
        this.getIsNewCusm(busAcctInfo);
        this.getCaHabit(busAcctInfo);
        this.getIsFrz(busAcctInfo);
        this.getBusStatusTag(busAcctInfo);
    }

    /**
     * 存续状态
     * 存续、注吊销
     * 按企查查中匹配
     */
    private void getBusStatusTag(BusAcctInfo busAcctInfo) {

        CusmTagRelation cusmTagRelation = new CusmTagRelation();
        cusmTagRelation.setBusCusmInfoId(busAcctInfo.getId());

        String cusmTagId = "";
        // 获取企查查信息
        QccQryAll qccQryAll = qccQryAllService.getOne(
                new LambdaQueryWrapper<QccQryAll>()
                        .eq(QccQryAll::getCoreNm, busAcctInfo.getCusmNm())
        );

        if (qccQryAll != null) {
            // 获取全部注吊销状态
            List<String> rvkdStaList = new ArrayList<>();
            rvkdStaList.add(CompanyStatusEnum.SHUT1.getIndex());
            rvkdStaList.add(CompanyStatusEnum.BLANK.getIndex());
            rvkdStaList.add(CompanyStatusEnum.SHUT2.getIndex());
            rvkdStaList.add(CompanyStatusEnum.SHUT3.getIndex());
            rvkdStaList.add(CompanyStatusEnum.SHUT4.getIndex());
            rvkdStaList.add(CompanyStatusEnum.SHUT5.getIndex());
            rvkdStaList.add(CompanyStatusEnum.SHUT6.getIndex());
            rvkdStaList.add(CompanyStatusEnum.SHUT7.getIndex());
            rvkdStaList.add(CompanyStatusEnum.SHUT8.getIndex());
            rvkdStaList.add(CompanyStatusEnum.SHUT9.getIndex());
            // 包含则为注吊销，不包含则为存续
            if (rvkdStaList.contains(qccQryAll.getSignSta())) {
                cusmTagId = cusmTagListService.getOne(
                        new LambdaQueryWrapper<CusmTagList>()
                                .eq(CusmTagList::getTagItem, "注吊销")
                ).getId();
            } else {
                cusmTagId = cusmTagListService.getOne(
                        new LambdaQueryWrapper<CusmTagList>()
                                .eq(CusmTagList::getTagItem, "存续")
                ).getId();
            }

            cusmTagRelation.setCusmTagId(cusmTagId);
            this.save(cusmTagRelation);
        }
    }

    /**
     * 是否为新开户
     * 新开户、存量
     * 开户至今小于143天,为新开账户未对账
     */
    private void getIsNewCusm(BusAcctInfo busAcctInfo) {
        CusmTagRelation cusmTagRelation = new CusmTagRelation();
        cusmTagRelation.setBusCusmInfoId(busAcctInfo.getId());

        String cusmTagId = "";
        if (busAcctInfo.getOacctDate() != null) {
            long time = busAcctInfo.getOacctDate().getTime();
            LocalDate oAcctLocalDate = Instant
                    .ofEpochMilli(busAcctInfo.getOacctDate().getTime())
                    .atZone(ZoneId.systemDefault())
                    .toLocalDate();

            long betweenDays = ChronoUnit.DAYS.between(oAcctLocalDate, LocalDate.now());

            // 开户至今小于143天,为新开账户未对账
            if (betweenDays < newCusmDaysMark) {
                cusmTagId = cusmTagListService.getOne(
                        new LambdaQueryWrapper<CusmTagList>()
                                .eq(CusmTagList::getTagItem, "新开户")
                ).getId();
            } else {
                cusmTagId = cusmTagListService.getOne(
                        new LambdaQueryWrapper<CusmTagList>()
                                .eq(CusmTagList::getTagItem, "存量")
                ).getId();
            }

            cusmTagRelation.setCusmTagId(cusmTagId);
            this.save(cusmTagRelation);
        }
    }

    /**
     * 对账习惯
     * 好、一般、差
     * 提取所有“回执查询”中近半年的账单回执距离日，计算每个协议号的对账距离日进行平均计算，
     * 评出账户的对账习惯【良好（1-10日内对账）、一般（11-30日内对账）、较差（30日后对账或未对账）】
     */
    private void getCaHabit(BusAcctInfo busAcctInfo) {
        CusmTagRelation cusmTagRelation = new CusmTagRelation();
        cusmTagRelation.setBusCusmInfoId(busAcctInfo.getId());

        String cusmTagId = "";

        List<Integer> daysCountList = new ArrayList<>();
        // 获取半年前的日期
        // 获取当前时间
        Calendar calendar = Calendar.getInstance();
        // 将时间往前推半年
        calendar.add(Calendar.MONTH, -6);
        // 获取半年之前那一天的Date对象
        Date dateBeforeHalfYear = calendar.getTime();

        // 根据客户号和日期去找协议号
        List<Cac> cacList = cacService.list(
                new LambdaQueryWrapper<Cac>()
                        .eq(Cac::getCusmNo, busAcctInfo.getCusmNo())
                        .ge(Cac::getCaCreateDate, dateBeforeHalfYear)
        );
        // 根据协议号找回执查询清单
        Set<String> protocalNoSet = cacList.stream()
                .map(Cac::getCaProtocolNo)
                .collect(Collectors.toSet());
        for (String protocalNo : protocalNoSet) {
            List<CaRtnList> caRtnLists = caRtnListService.list(
                    new LambdaQueryWrapper<CaRtnList>()
                            .eq(CaRtnList::getProtocolNo, protocalNo)
            );
            // 大于0表示存在回执
            if (caRtnLists.size() > 0) {
                for (CaRtnList caRtnList : caRtnLists) {
                    Date rtnSignDate = caRtnList.getRtnSignDate();
                    Date caCreateDate = cacService.getOne(
                            new LambdaQueryWrapper<Cac>()
                                    .eq(Cac::getCaProtocolNo, protocalNo)
                                    .eq(Cac::getCaNo, caRtnList.getCaNo())
                    ).getCaCreateDate();
                    // 将 Date 转换为 Instant
                    Instant instant1 = rtnSignDate.toInstant();
                    Instant instant2 = caCreateDate.toInstant();

                    // 使用 Duration 类获取时间间隔
                    Duration duration = Duration.between(instant1, instant2);

                    // 获取相差天数
                    long days = duration.toDays();
                    Integer integer = Math.toIntExact(days);
                    daysCountList.add(integer);
                }
            }
        }

        if (daysCountList.size() == 0) {
            // 没有值表示未对账，返回差
            cusmTagId = cusmTagListService.getOne(
                    new LambdaQueryWrapper<CusmTagList>()
                            .eq(CusmTagList::getTagItem, "差")
            ).getId();
        } else {
            // 使用 Stream API 计算平均值，并格式化为两位小数
            double averageDays = daysCountList
                    .stream()
                    .mapToInt(Integer::intValue)
                    .average().orElse(0);
            // 良好（1-10日内对账）、一般（11-30日内对账）、较差（30日后对账或未对账）
            if (averageDays >= 1 && averageDays <= 10) {
                cusmTagId = cusmTagListService.getOne(
                        new LambdaQueryWrapper<CusmTagList>()
                                .eq(CusmTagList::getTagItem, "好")
                ).getId();
            } else if (averageDays > 10 && averageDays <= 30) {
                cusmTagId = cusmTagListService.getOne(
                        new LambdaQueryWrapper<CusmTagList>()
                                .eq(CusmTagList::getTagItem, "一般")
                ).getId();
            } else if (averageDays > 30) {
                cusmTagId = cusmTagListService.getOne(
                        new LambdaQueryWrapper<CusmTagList>()
                                .eq(CusmTagList::getTagItem, "差")
                ).getId();
            }
        }
        cusmTagRelation.setCusmTagId(cusmTagId);
        this.save(cusmTagRelation);
    }

    /**
     * 冻结情况
     * 已冻结
     * 如有冻结，显示冻结原因，到期日为多少
     */
    private void getIsFrz(BusAcctInfo busAcctInfo) {
        // 根据冻结到期日判断是否已冻结
        if (busAcctInfo.getFrzSropDate() != null) {
            int result = busAcctInfo.getFrzSropDate().compareTo(new Date());
            // 大于0则冻结到期日在当天之后，视为冻结
            if (result > 0) {
                CusmTagRelation cusmTagRelation = new CusmTagRelation();
                cusmTagRelation.setBusCusmInfoId(busAcctInfo.getId());

                String cusmTagId = cusmTagListService.getOne(
                        new LambdaQueryWrapper<CusmTagList>()
                                .eq(CusmTagList::getTagItem, "已冻结")
                ).getId();

                cusmTagRelation.setCusmTagId(cusmTagId);
                this.save(cusmTagRelation);
            }
        }
    }

    // 风险特征
    private void genriskTag(BusAcctInfo busAcctInfo) {
        this.getRvkdMuchDeal(busAcctInfo);
        this.getLastQuarterMuchDeal(busAcctInfo);
        this.getAmlSysRskClass(busAcctInfo);
        this.getAgeRisk(busAcctInfo);
        this.getNonlocalBigDeal(busAcctInfo);
        this.getQccRisk(busAcctInfo);
    }

    /**
     * 工商注吊销但上月交易频繁
     * 工商注吊销但上月交易频繁
     * 存续状态有“销”字,上月交易20笔以上,"工商已注吊销但上月交易频繁
     */
    private void getRvkdMuchDeal(BusAcctInfo busAcctInfo) {
        // 获取企查查信息
        QccQryAll qccQryAll = qccQryAllService.getOne(
                new LambdaQueryWrapper<QccQryAll>()
                        .eq(QccQryAll::getCoreNm, busAcctInfo.getCusmNm())
        );
        if (qccQryAll != null) {
            // 存续状态有“销”字
            List<String> rvkdStaList = new ArrayList<>();
            rvkdStaList.add(CompanyStatusEnum.SHUT1.getIndex());
            rvkdStaList.add(CompanyStatusEnum.SHUT4.getIndex());
            rvkdStaList.add(CompanyStatusEnum.SHUT5.getIndex());
            rvkdStaList.add(CompanyStatusEnum.OPENING9.getIndex());
            rvkdStaList.add(CompanyStatusEnum.OPENING10.getIndex());
            rvkdStaList.add(CompanyStatusEnum.SHUT6.getIndex());
            rvkdStaList.add(CompanyStatusEnum.SHUT7.getIndex());
            rvkdStaList.add(CompanyStatusEnum.SHUT8.getIndex());
            rvkdStaList.add(CompanyStatusEnum.SHUT9.getIndex());
            if (rvkdStaList.contains(qccQryAll.getSignSta()) &&
                    Integer.parseInt(busAcctInfo.getMonFinaceTrans()) > 20) {
                CusmTagRelation cusmTagRelation = new CusmTagRelation();
                cusmTagRelation.setBusCusmInfoId(busAcctInfo.getId());

                String cusmTagId = cusmTagListService.getOne(
                        new LambdaQueryWrapper<CusmTagList>()
                                .eq(CusmTagList::getTagItem, "工商注吊销但上月交易频繁")
                ).getId();

                cusmTagRelation.setCusmTagId(cusmTagId);
                this.save(cusmTagRelation);
            }
        }
    }

    /**
     * 上季度交易频繁
     * 未对账交易频繁
     * 3个月内交易800以上,"上季度交易频繁
     */
    private void getLastQuarterMuchDeal(BusAcctInfo busAcctInfo) {
        if (busAcctInfo.getLastThMonsTrans() != null
                && Integer.parseInt(busAcctInfo.getLastThMonsTrans()) > 800) {
            CusmTagRelation cusmTagRelation = new CusmTagRelation();
            cusmTagRelation.setBusCusmInfoId(busAcctInfo.getId());

            String cusmTagId = cusmTagListService.getOne(
                    new LambdaQueryWrapper<CusmTagList>()
                            .eq(CusmTagList::getTagItem, "未对账交易频繁")
            ).getId();

            cusmTagRelation.setCusmTagId(cusmTagId);
            this.save(cusmTagRelation);
        }
    }

    /**
     * 反洗钱等级
     * 高风险、中高风险、高风险
     * 反洗钱风险等级：3、高风险 D、中高风险 E、高风险
     */
    private void getAmlSysRskClass(BusAcctInfo busAcctInfo) {
        if ("3".equals(busAcctInfo.getAmlSysRskClass())
                || "E".equals(busAcctInfo.getAmlSysRskClass())) {
            CusmTagRelation cusmTagRelation = new CusmTagRelation();
            cusmTagRelation.setBusCusmInfoId(busAcctInfo.getId());

            String cusmTagId = cusmTagListService.getOne(
                    new LambdaQueryWrapper<CusmTagList>()
                            .eq(CusmTagList::getTagItem, "高风险")
            ).getId();

            cusmTagRelation.setCusmTagId(cusmTagId);
            this.save(cusmTagRelation);
        } else if ("D".equals(busAcctInfo.getAmlSysRskClass())) {
            CusmTagRelation cusmTagRelation = new CusmTagRelation();
            cusmTagRelation.setBusCusmInfoId(busAcctInfo.getId());

            String cusmTagId = cusmTagListService.getOne(
                    new LambdaQueryWrapper<CusmTagList>()
                            .eq(CusmTagList::getTagItem, "中高风险")
            ).getId();

            cusmTagRelation.setCusmTagId(cusmTagId);
            this.save(cusmTagRelation);
        }

    }

    /**
     * 法人年龄
     * 财务超龄、法人未达龄
     * 按财务负责人与法人身份证判断年龄，
     * 财务负责人已满70岁，请核实该账户真实使用情况
     * 或法人未满18岁，请核实该账户真实使用情况
     */
    private void getAgeRisk(BusAcctInfo busAcctInfo) {
        // 判断法人年龄
        if (busAcctInfo.getLglRpstId() != null
                && this.getAgeByCusmIdCardNumber(busAcctInfo.getLglRpstId()) < 18) {
            CusmTagRelation cusmTagRelation = new CusmTagRelation();
            cusmTagRelation.setBusCusmInfoId(busAcctInfo.getId());

            String cusmTagId = cusmTagListService.getOne(
                    new LambdaQueryWrapper<CusmTagList>()
                            .eq(CusmTagList::getTagItem, "法人未达龄")
            ).getId();

            cusmTagRelation.setCusmTagId(cusmTagId);
            this.save(cusmTagRelation);
        }
        // 判断财务年龄
        if (busAcctInfo.getFinacePrincipalId() != null
                && this.getAgeByCusmIdCardNumber(busAcctInfo.getFinacePrincipalId()) >= 70) {
            CusmTagRelation cusmTagRelation = new CusmTagRelation();
            cusmTagRelation.setBusCusmInfoId(busAcctInfo.getId());

            String cusmTagId = cusmTagListService.getOne(
                    new LambdaQueryWrapper<CusmTagList>()
                            .eq(CusmTagList::getTagItem, "财务超龄")
            ).getId();

            cusmTagRelation.setCusmTagId(cusmTagId);
            this.save(cusmTagRelation);
        }
    }

    // 根据身份证号获取年龄
    private int getAgeByCusmIdCardNumber(String idCardNumber) {
        String birthDateStr = idCardNumber.substring(6, 14);
        LocalDate birthDate = LocalDate.parse(birthDateStr, DateTimeFormatter.ofPattern("yyyyMMdd"));
        LocalDate currentDate = LocalDate.now();
        return Period.between(birthDate, currentDate).getYears();
    }

    /**
     * 外地注册单笔交易
     * 外地注册大额交易
     * 注册地址无“湖南”字眼，且上月交易最大金额超过10万：外地注册，上月单笔交易10万以上
     */
    private void getNonlocalBigDeal(BusAcctInfo busAcctInfo) {
        if (busAcctInfo.getSignAddr() != null
                && busAcctInfo.getMonSnglBigNum() != null
                && !busAcctInfo.getSignAddr().matches(".*湖南.*")
                && Integer.parseInt(busAcctInfo.getMonSnglBigNum()) > 100000) {
            CusmTagRelation cusmTagRelation = new CusmTagRelation();
            cusmTagRelation.setBusCusmInfoId(busAcctInfo.getId());

            String cusmTagId = cusmTagListService.getOne(
                    new LambdaQueryWrapper<CusmTagList>()
                            .eq(CusmTagList::getTagItem, "外地注册大额交易")
            ).getId();

            cusmTagRelation.setCusmTagId(cusmTagId);
            this.save(cusmTagRelation);
        }
    }

    /**
     * 企查查风险内容
     * 新闻舆情数量较多、经营异常数量较多、严重违法数量较多、行政处罚数量较多、
     * 税收违法详情数量较多、环保处罚数量较多、被执行人数量较多、裁判文书数量较多
     * <p>
     * 算出所有新闻舆情数量、经营异常数量、严重违法数量、行政处罚数量、税收违法详情数量、
     * 环保处罚数量、被执行人数量、裁判文书数量，计算不为零的平均数，当超过平均数时显示：
     * 新闻舆情数量较多、经营异常数量较多、严重违法数量较多、行政处罚数量较多、税收违法详情数量较多、
     * 环保处罚数量较多、被执行人数量较多、裁判文书数量较多
     */
    private void getQccRisk(BusAcctInfo busAcctInfo) {
        // 获取企查查信息
        QccQryAll qccQryAll = qccQryAllService.getOne(
                new LambdaQueryWrapper<QccQryAll>()
                        .eq(QccQryAll::getCoreNm, busAcctInfo.getCusmNm())
        );
        if (qccQryAll != null) {
            // 新闻舆情数量
            int pubStmtCnt = Integer.parseInt(qccQryAll.getPubStmtCnt());
            // 经营异常数量
            int oprtUnuslCnt = Integer.parseInt(qccQryAll.getPubStmtCnt());
            // 严重违法数量
            int srsIllgCnt = Integer.parseInt(qccQryAll.getPubStmtCnt());
            // 行政处罚数量
            int admsrtPnlyCnt = Integer.parseInt(qccQryAll.getAdmsrtPnlyCnt());
            // 税收违法详情数量
            int taxIllgCnt = Integer.parseInt(qccQryAll.getTaxIllgCnt());
            // 环保处罚数量
            int evrmtPnlyCnt = Integer.parseInt(qccQryAll.getTaxIllgCnt());
            // 失信执行人数量
            int dshnstPsnCnt = Integer.parseInt(qccQryAll.getTaxIllgCnt());
            // 裁判文书数量
            int jdgmtTxtCnt = Integer.parseInt(qccQryAll.getTaxIllgCnt());

            Map<String, Integer> probCntMap = new HashMap<>();
            Map<String, String> probTagMap = new HashMap<>();
            if (pubStmtCnt > 0) {
                probCntMap.put("pubStmtCnt", pubStmtCnt);
                probTagMap.put("pubStmtCnt", "新闻舆情数量较多");
            }
            if (oprtUnuslCnt > 0) {
                probCntMap.put("oprtUnuslCnt", oprtUnuslCnt);
                probTagMap.put("pubStmtCnt", "经营异常数量较多");
            }
            if (srsIllgCnt > 0) {
                probCntMap.put("srsIllgCnt", srsIllgCnt);
                probTagMap.put("pubStmtCnt", "严重违法数量较多");
            }
            if (admsrtPnlyCnt > 0) {
                probCntMap.put("admsrtPnlyCnt", admsrtPnlyCnt);
                probTagMap.put("pubStmtCnt", "行政处罚数量较多");
            }
            if (taxIllgCnt > 0) {
                probCntMap.put("taxIllgCnt", taxIllgCnt);
                probTagMap.put("pubStmtCnt", "税收违法详情数量较多");
            }
            if (evrmtPnlyCnt > 0) {
                probCntMap.put("evrmtPnlyCnt", evrmtPnlyCnt);
                probTagMap.put("pubStmtCnt", "环保处罚数量较多");
            }
            if (dshnstPsnCnt > 0) {
                probCntMap.put("dshnstPsnCnt", dshnstPsnCnt);
                probTagMap.put("pubStmtCnt", "被执行人数量较多");
            }
            if (jdgmtTxtCnt > 0) {
                probCntMap.put("jdgmtTxtCnt", jdgmtTxtCnt);
                probTagMap.put("pubStmtCnt", "裁判文书数量较多");
            }

            BigDecimal sum = BigDecimal.valueOf(0); // 注意初始化BigDecimal时传入0
            Set<String> keySet = probCntMap.keySet();
            for (String probKey : keySet) {
                sum.add(BigDecimal.valueOf(probCntMap.get(probKey)));
            }
            BigDecimal average = sum.divide(BigDecimal.valueOf(keySet.size()), 2, BigDecimal.ROUND_HALF_UP);
            for (String probKey : keySet) {
                // BigDecimal.compareTo 大于0表示左大于右
                if (BigDecimal.valueOf(probCntMap.get(probKey)).compareTo(average) > 0) {
                    CusmTagRelation cusmTagRelation = new CusmTagRelation();
                    cusmTagRelation.setBusCusmInfoId(busAcctInfo.getId());

                    String cusmTagId = cusmTagListService.getOne(
                            new LambdaQueryWrapper<CusmTagList>()
                                    .eq(CusmTagList::getTagItem, probTagMap.get(probKey))
                    ).getId();
                    cusmTagRelation.setCusmTagId(cusmTagId);
                    this.save(cusmTagRelation);
                }
            }
        }
    }
}
